package com.esd.crm.controller;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.esd.crm.Constants;
import com.esd.crm.entity.Customer;
import com.esd.crm.entity.Orders;
import com.esd.crm.entity.Product;
import com.esd.crm.service.CustomerService;
import com.esd.crm.service.OrdersService;
import com.esd.crm.service.ProductService;

@Controller
@RequestMapping("/security")
public class ProductController {

	private static final Logger logger = LogManager.getLogger(ProductController.class);

	@Autowired
	private ProductService productService;
	@Autowired
	private CustomerService customerService;
	@Autowired
	private OrdersService ordersService;

	/**
	 * 同步计算合计
	 */

	private void scyUpdateCustomerTotal(String orderNumber) {

		Map<String, Object> param = new HashMap<String, Object>();
		param.put("orderNumber", orderNumber);
		Orders record = ordersService.selectNumberTotalByOrderNumber(param);
		Orders update = ordersService.selectByOrderNumber(param);
		update.setTotal(record.getTotal());
		if (record.getTotal() == null) {
			record.setTotal(new BigDecimal(0));
		}
		update.setPayable(record.getTotal().subtract(update.getPaid()));
		update.setNumber(record.getNumber());
		logger.info(record.toString());
		ordersService.updateByPrimaryKeySelective(update);
	}

	/**
	 * 跳转添加产品页
	 */
	@RequestMapping(value = "/addProduct", method = RequestMethod.GET)
	public ModelAndView addProductGet(HttpSession session, HttpServletRequest request) {
		logger.info("跳转添加产品页");
		String orderNumber = request.getParameter("orderNumber");
		if (StringUtils.isBlank(orderNumber)) {
			ModelAndView mv = new ModelAndView("product/product");
			return mv;
		}
		logger.info("orderNumber:" + orderNumber);
		// Customer c = customerService.selectByPrimaryKey(Integer.valueOf(customerId));
		ModelAndView mv = new ModelAndView("product/product_add");
		mv.addObject("orderNumber", orderNumber);
		// mv.addObject("card", c.getCard());
		// mv.addObject("name", c.getName());
		// BigDecimal total = productService.selectSumAmout(c.getId());
		// mv.addObject("total", total);

		return mv;
	}

	/**
	 * 添加产品
	 * 
	 * @param session
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/addProduct", method = RequestMethod.POST)
	public ModelAndView addProductPost(HttpSession session, HttpServletRequest request, RedirectAttributes redirectAttributes) {
		logger.info("添加产品请求");
		Integer userid = Integer.valueOf(session.getAttribute(Constants.USER_ID).toString());
		String orderNumber = request.getParameter("orderNumber");
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("orderNumber", orderNumber);
		Orders o = ordersService.selectByOrderNumber(param);

		if (StringUtils.isBlank(orderNumber)) {
			// return new ModelAndView("redirect:/security/order");
			logger.info("订单号为空");
		}
		// String orderNumber = CalendarUtil.getOrderNumber();
		// String customerId = request.getParameter("customerId");
		String product = request.getParameter("product");
		String specification = request.getParameter("specification");
		String texture = request.getParameter("texture");
		String thickness = request.getParameter("thickness");
		String color = request.getParameter("color");
		String number = request.getParameter("number");
		String unit = request.getParameter("unit");
		String amout = request.getParameter("amout");
		String remark = request.getParameter("remark");
		Product p = new Product();
		p.setOrdernumber(orderNumber);
		p.setCustomerid(o.getCustomerid());
		p.setProduct(product);
		p.setSpecification(specification);
		p.setTexture(texture);
		p.setThickness(thickness);
		p.setColor(color);
		p.setNumber(number);
		p.setUnit(new BigDecimal(unit));
		p.setAmout(new BigDecimal(amout));
		p.setRemark(remark);

		p.setCreatetime(new Date());
		p.setCreateuser(userid);
		productService.insert(p);
		redirectAttributes.addAttribute("orderNumber", orderNumber);
		// 同步更新合计
		scyUpdateCustomerTotal(p.getOrdernumber());
		return new ModelAndView("redirect:/security/successAndClose");
	}

	@RequestMapping(value = "/product", method = RequestMethod.GET)
	public ModelAndView productGet(HttpSession session, HttpServletRequest request) {
		String orderNumber = request.getParameter("orderNumber");
		ModelAndView mv = new ModelAndView("product/product");
		if (StringUtils.isNotBlank(orderNumber)) {
			mv.addObject("orderNumber", orderNumber);
		}
		return mv;
	}

	@RequestMapping(value = "/product", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> productPost(HttpSession session, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String orderNumber = request.getParameter("orderNumber");
		String name = request.getParameter("name");
		String createTime = request.getParameter("createTime");
		int totle = 1;
		List<Product> list = null;
		// 组合查询参数
		int page = Integer.valueOf(request.getParameter("page"));
		Map<String, Object> param = new HashMap<String, Object>();
		if (StringUtils.isNotBlank(orderNumber)) {
			param.put("orderNumber", orderNumber);
		}
		if (StringUtils.isNotBlank(name)) {
			param.put("name", name);
		}
		if (StringUtils.isNotBlank(createTime)) {
			param.put("createTime", createTime);
		}
		param.put("page", (page - 1) * 20);
		param.put("totle", 20);
		list = productService.selectByParam(param);
		totle = productService.selectByParamCount(param);
		int u = totle % 20;
		int pageCount = 1;
		if (u > 0) {
			pageCount = totle / 20 + 1;
		} else {
			pageCount = totle / 20;
		}
		map.put(Constants.LIST, list);
		map.put(Constants.TOTLE, totle);
		map.put(Constants.TOTLE_PAGE, pageCount);
		return map;
	}

	/**
	 * 跳转添加产品页
	 */
	@RequestMapping(value = "/updateProduct", method = RequestMethod.GET)
	public ModelAndView updateProductGet(HttpSession session, HttpServletRequest request) {
		logger.info("跳转更新产品页");
		String id = request.getParameter("id");
		Product p = productService.selectByPrimaryKey(Integer.valueOf(id));
		ModelAndView mv = new ModelAndView("product/product_update");
		mv.addObject("id", p.getId());
		mv.addObject("product", p.getProduct());
		mv.addObject("specification", p.getSpecification());
		mv.addObject("texture", p.getTexture());
		mv.addObject("thickness", p.getThickness());
		mv.addObject("color", p.getColor());
		mv.addObject("number", p.getNumber());
		mv.addObject("unit", p.getUnit());
		mv.addObject("amout", p.getAmout());
		mv.addObject("remark", p.getRemark());
		Customer c = customerService.selectByPrimaryKey(Integer.valueOf(p.getCustomerid()));
		mv.addObject("customerId", c.getId());
		mv.addObject("card", c.getCard());
		mv.addObject("name", c.getName());
		BigDecimal total = productService.selectSumAmout(p.getCustomerid());
		mv.addObject("total", total);
		return mv;
	}

	/**
	 * 更新产品
	 * 
	 * @param session
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/updateProduct", method = RequestMethod.POST)
	public ModelAndView updateProductPost(HttpSession session, HttpServletRequest request, RedirectAttributes redirectAttributes) {
		Integer userid = Integer.valueOf(session.getAttribute(Constants.USER_ID).toString());
		logger.info("跳转更新产品页");
		String id = request.getParameter("id");
		Product p = productService.selectByPrimaryKey(Integer.valueOf(id));

		String product = request.getParameter("product");
		String specification = request.getParameter("specification");
		String texture = request.getParameter("texture");
		String thickness = request.getParameter("thickness");
		String color = request.getParameter("color");
		String number = request.getParameter("number");
		String unit = request.getParameter("unit");
		String amout = request.getParameter("amout");
		String remark = request.getParameter("remark");

		p.setProduct(product);
		p.setSpecification(specification);
		p.setTexture(texture);
		p.setThickness(thickness);
		p.setColor(color);
		p.setNumber(number);
		p.setUnit(new BigDecimal(unit));
		p.setAmout(new BigDecimal(amout));
		p.setRemark(remark);

		p.setCreatetime(new Date());
		p.setUpdatetime(new Date());
		p.setUpdateuser(userid);
		productService.updateByPrimaryKeySelective(p);
		redirectAttributes.addAttribute("orderNumber", p.getOrdernumber());
		// 同步更新合计
		scyUpdateCustomerTotal(p.getOrdernumber());

		return new ModelAndView("redirect:/security/successAndClose");
	}

	/**
	 * 跳转添加产品页
	 */
	@RequestMapping(value = "/deleteProduct", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> deleteProductPost(HttpSession session, HttpServletRequest request) {
		logger.info("删除产品");
		Map<String, Object> map = new HashMap<String, Object>();
		String id = request.getParameter("id");
		Product p = productService.selectByPrimaryKey(Integer.valueOf(id));
		if (p != null) {
			int i = productService.deleteByPrimaryKey(Integer.valueOf(id));
			if (i != 0) {
				map.put("message", "删除成功!");
			}
		}
		// 同步更新合计
		scyUpdateCustomerTotal(p.getOrdernumber());
		return map;
	}
}
